import 'package:flutter_admin/pages/common/cry/cry_button_bar.dart';
import 'package:flutter_admin/pages/common/cry/cry_buttons.dart';
import 'package:flutter_admin/pages/common/cry/form/cry_input.dart';
import 'package:flutter_admin/pages/common/cry/form/cry_select.dart';
import 'package:flutter_admin/pages/common/cry/form/cry_select_date.dart';
import 'package:flutter_admin/pages/common/cry/model/order_item_model.dart';
import 'package:flutter/material.dart';
import 'package:flutter_admin/pages/common/cry/cry_button.dart';
import 'package:flutter_admin/pages/common/cry/cry_data_table.dart';
import 'package:flutter_admin/api/odoo/stock_picking_odoo_api.dart';
import 'package:flutter_admin/constants/enum.dart';
import 'package:flutter_admin/pages/common/cry/model/page_model.dart';
import 'package:flutter_admin/pages/common/cry/model/response_body_api.dart';
import 'package:flutter_admin/models/odoo/stock_picking.dart';
import 'package:flutter_admin/pages/odoo/stock_picking/stock_picking_dialog.dart';
import 'package:flutter_admin/pages/common/cry/vo/select_option_vo.dart';
import 'package:flutter_admin/api/odoo/dynamic_data_api.dart';
import 'package:flutter_admin/utils/adaptive_util.dart';
import 'package:flutter_admin/utils/utils.dart';
import 'package:flutter_admin/pages/odoo/stock_picking/stock_production_list.dart';
import 'package:intl/intl.dart';
import 'package:quiver/strings.dart';

class WorkshopTransferSearchList extends StatefulWidget {
  WorkshopTransferSearchList({Key? key}) : super(key: key);
  @override
  _WorkshopTransferSearchListState createState() =>
      _WorkshopTransferSearchListState();
}

class _WorkshopTransferSearchListState
    extends State<WorkshopTransferSearchList> {
  final GlobalKey<CryDataTableState> tableKey = GlobalKey<CryDataTableState>();
  final GlobalKey<FormState> formKey = GlobalKey<FormState>();
  final GlobalKey<ScaffoldState> scaffoldStateKey = GlobalKey<ScaffoldState>();
  PageModel page =
      PageModel(orders: [OrderItemModel(column: 'create_date', asc: false)]);
  StockPicking stockPicking = StockPicking();
  List<StockPicking> selectedList = [];
  late List<SelectOptionVO> locationtypeList = [];

  //工厂名称
  List<SelectOptionVO> locationIdList = [];
  //车间名称
  List<SelectOptionVO> workshopIdList = [];
  var workshopId = '';
  DateFormat format = DateFormat('yyyy-MM-dd');
  @override
  void initState() {
    super.initState();
    stockPicking.createDateStart = Utils.getDate();
    stockPicking.createDateEnd = Utils.getDate();
    WidgetsBinding.instance!.addPostFrameCallback((c) {
      _query();
      _loadSelectVO();
    });
  }

  _loadSelectVO() async {
    workshopIdList = await DynamicDataApi.getModelSelect(
        active: false,
        model: "hr.department",
        name: "complete_name",
        key: 'parent_id',
        operator: "!=",
        val: null);
    setState(() {});
  }

  @override
  Widget build(BuildContext context) {
    var form = Form(
      key: formKey,
      child: Wrap(
        children: <Widget>[
          CrySelectDate(
            context,
            width: 180,
            label: '移库开始时间',
            lastDate: isNotBlank(stockPicking.createDateEnd)
                ? format.parse(stockPicking.createDateEnd!)
                : null,
            value: stockPicking.createDateStart,
            onDateChange: (v) {
              formKey.currentState?.save();
              stockPicking.createDateStart = v;
              setState(() {});
            },
            onSaved: (v) {
              stockPicking.createDateStart = v;
            },
          ),
          CrySelectDate(
            context,
            width: 180,
            label: '移库结束时间',
            firstDate: isNotBlank(stockPicking.createDateStart)
                ? format.parse(stockPicking.createDateStart!)
                : null,
            value: stockPicking.createDateEnd,
            onDateChange: (v) {
              formKey.currentState?.save();
              stockPicking.createDateEnd = v;
              setState(() {});
            },
            onSaved: (v) {
              stockPicking.createDateEnd = v;
            },
          ),
          CrySelect(
            label: '生产车间',
            width: 280,
            dataList: this.workshopIdList,
            value: stockPicking.workshopId,
            onSaved: (v) => {stockPicking.workshopId = v},
            onChange: (v) async {
              if (workshopId != v) {
                formKey.currentState!.save();
                workshopId = v;
                stockPicking.locationId = null;
                try {
                  locationIdList = await DynamicDataApi.getModelSelect(
                      active: false,
                      model: "stock.location",
                      name: "complete_name",
                      key: 'workshop_id',
                      val: int.parse(v),
                      key2: "comment",
                      val2: "ZZK");
                } catch (e) {
                  locationIdList = [];
                }
                setState(() {});
              }
            },
          ),
          CrySelect(
            label: '源库房',
            width: 380,
            dataList: locationIdList,
            value: stockPicking.locationId,
            onSaved: (v) => {stockPicking.locationId = v},
          ),
          CryInput(
            width: 180,
            label: '生产订单号',
            value: stockPicking.productorderno,
            onSaved: (v) {
              stockPicking.productorderno = v;
            },
          ),
        ],
      ),
    );

    CryDataTable table = CryDataTable(
      key: tableKey,
      title: "数据列表",
      actions: !isDisplayDesktop(context)
          ? [
              _operationList(),
            ]
          : [],
      onPageChanged: (firstRowIndex) {
        page.current = (firstRowIndex ~/ page.size + 1);
        _loadData();
      },
      onRowsPerPageChanged: (int size) {
        page.size = size;
        page.current = 1;
        _loadData();
      },
      onSelectChanged: (Map selected) {
        this.setState(() {});
      },
      columns: [
        DataColumn(label: Text('生产订单号')),
        DataColumn(label: Text('源库房')),
        DataColumn(label: Text('目标库房')),
        DataColumn(label: Text('操作人')),
        DataColumn(label: Text('操作时间')),
        DataColumn(label: Text('接收人')),
      ],
      getCells: (m) {
        StockPicking stockPicking = StockPicking.fromMap(m);
        return [
          DataCell(Text(stockPicking.productorderno ?? '--')),
          DataCell(Text(stockPicking.locationName ?? '--')),
          DataCell(Text(stockPicking.locationDestName ?? '--')),
          DataCell(Text(stockPicking.createUid ?? '--')),
          DataCell(Text(Utils.timeUTC(stockPicking.createDate ?? '--'))),
          DataCell(Text(stockPicking.writeUid ?? '--')),
        ];
      },
    );
    _getSelectList();
    CryButtonBar buttonBar = CryButtonBar(
      children: <Widget>[
        CryButtons.query(context, () => _query()),
        CryButtons.reset(context, () => _reset()),
        // CryButtons.dmsFile(
        //   context,
        //   selectedList.length == 1 ? () => _dmsFile(selectedList[0]) : null,
        // ),
        CryButton(
          label: "产品明细",
          iconData: Icons.view_headline,
          onPressed: selectedList.length == 1
              ? () => _openDetail(selectedList[0])
              : null,
        )
      ],
    );
    var result = Scaffold(
      key: scaffoldStateKey,
      body: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          SizedBox(height: 10),
          isDisplayDesktop(context) ? form : Container(),
          isDisplayDesktop(context) ? buttonBar : Container(),
          Expanded(child: SingleChildScrollView(child: table)),
        ],
      ),
    );
    return result;
  }

  _reset() {
    stockPicking = StockPicking();
    locationIdList = [];
    formKey.currentState!.reset();
    stockPicking.createDateStart = Utils.getDate();
    stockPicking.createDateEnd = Utils.getDate();
    _loadData();
  }

  _query() {
    formKey.currentState?.save();
    tableKey.currentState?.pageTo(0);
    _loadData();
  }

  _loadData() async {
    ResponseBodyApi responseBodyApi = await StockPickingOdooApi.TransferRecord(
        data: {
          "page": page,
          "domainList": stockPicking.toDomainListTransfer()
        });
    if (responseBodyApi.success!) {
      page = responseBodyApi.data != null ? responseBodyApi.data : PageModel();
      tableKey.currentState!.loadData(page);
      _getSelectList();
    }
  }

  _openDetail(StockPicking stockPicking) {
    Utils.fullscreenDialog(StockProductionList(
      stockPicking: stockPicking,
      flag: false,
    ));
  }

  _search() {
    return showDialog(
      context: context,
      builder: (BuildContext context) => Dialog(
        child: StockPickingDialog(),
      ),
    ).then((v) {
      if (v != null) {
        stockPicking = v;
        _query();
      }
    });
  }

  _getSelectList() {
    selectedList = tableKey.currentState
            ?.getSelectedList(page)
            .map<StockPicking>((e) => StockPicking.fromMapTransfer(e))
            .toList() ??
        [];
    setState(() {});
  }

  _operationList() {
    return PopupMenuButton(
      onSelected: (dynamic v) {
        if (v == OperationType.query) {
          _search();
        } else if (v == OperationType.dmsFile) {
          _openDetail(selectedList[0]);
        }
      },
      itemBuilder: (context) => <PopupMenuEntry<OperationType>>[
        PopupMenuItem<OperationType>(
          value: OperationType.query,
          child: ListTile(
            leading: const Icon(Icons.search),
            title: Text('查询'),
          ),
        ),
        PopupMenuItem<OperationType>(
          value: OperationType.dmsFile,
          enabled: selectedList.length == 1,
          child: ListTile(
            leading: const Icon(Icons.view_agenda_rounded),
            enabled: selectedList.length == 1,
            title: Text('产品信息'),
          ),
        ),
      ],
    );
  }
}
